import React, { useEffect, useRef, useState } from "react";
import { Button, Toast, NavBar } from "antd-mobile";

const MapComponent = () => {
  const mapContainer = useRef(null);
  const mapInstance = useRef(null);
  const [address, setAddress] = useState("");
  const [message, setMessage] = useState("");
  const [position, setPosition] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  // 初始化地图和自动打卡
  useEffect(() => {
    initMap();
    return () => mapInstance.current?.destroy();
  }, []);

  const initMap = async () => {
    if (!window.AMap) return;

    // 初始化地图
    mapInstance.current = new window.AMap.Map(mapContainer.current, {
      center: [115.4889, 38.8149], // 初始中心点
      resizeEnable: true,
      zoom: 16,
    });

    // 获取定位
    getLocationAndClockIn();
  };

  // 添加定位点标记
  const addMarker = (position) => {
    const marker = new window.AMap.Marker({
      position: new window.AMap.LngLat(position.lng, position.lat), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      title: "当前位置",
    });
    mapInstance.current.add(marker);
  };

  // 获取定位并打卡
  const getLocationAndClockIn = async () => {
    setIsLoading(true);
    try {
      // 1. 获取定位
      const position = await getCurrentPosition();
      console.log("position", position);

      // 2. 立即执行逆地理编码
      const currentAddress = await reverseGeocode(position);

      // 3. 添加标记
      addMarker(position);
    } catch (error) {
      handleError(error);
    } finally {
      setIsLoading(false);
    }
  };

  // 获取定位
  const getCurrentPosition = () => {
    return new Promise((resolve, reject) => {
      window.AMap.plugin("AMap.Geolocation", () => {
        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
        });

        geolocation.getCurrentPosition((status, result) => {
          if (status === "complete") {
            setPosition(result.position);
            resolve(result.position);
          } else {
            reject(new Error(result.message));
          }
        });
      });
    });
  };

  // 错误处理
  const handleError = (error) => {
    const errorMsg = error.response?.data?.error || error.message || "打卡失败";
    setMessage(errorMsg);
    Toast.show({
      icon: "fail",
      content: errorMsg,
    });
  };

  // 监听位置变化执行逆地理编码
  useEffect(() => {
    if (position) {
      reverseGeocode(position);
    }
  }, [position]);

  // 逆地理编码功能
  const reverseGeocode = async (pos) => {
    return new Promise((resolve) => {
      window.AMap.plugin("AMap.Geocoder", () => {
        const geocoder = new window.AMap.Geocoder({ city: "全国" });

        geocoder.getAddress([pos.lng, pos.lat], (status, result) => {
          console.log(result);
          if (status === "complete" && result.info === "OK") {
            const address = result.regeocode.formattedAddress.slice(0, 6);
            setAddress(address); // 更新状态用于显示
            resolve(address); // 返回解析结果
          }
        });
      });
    });
  };

  return (
    <div style={{ padding: 12 }}>
      {/* 地图容器 */}
      <div
        ref={mapContainer}
        style={{
          width: "100%",
          height: "40vh",
          borderRadius: 8,
          overflow: "hidden",
          marginBottom: 12,
        }}
      />

      {/* 位置信息 */}
      {position && (
        <div style={{ marginBottom: 12 }}>
          {/* <p>当前位置：</p> */}
          <p style={{ color: "#666", fontSize: 12 }}>{address}</p>
        </div>
      )}

      {/* 手动打卡按钮 */}
      <Button
        color="primary"
        loading={isLoading}
        onClick={getLocationAndClockIn}
        block
      >
        {isLoading ? "正在打卡..." : "重新定位"}
      </Button>
    </div>
  );
};

export default MapComponent;
